import * as XLSX from "xlsx";
import FileSaver from "file-saver";
import { tableHeader } from "@/views/purchase-receipt/data";
import { Message, Loading } from "element-ui";
import { tansParams, blobValidate } from "@/utils/cmsNeed";
import { cafReq } from "@/requests";
import { baseURL } from "@/requests/api/menu";
import { getErrorCodeDesc } from "@/requests/base/code";
// 导出Excel模板表格
export const exportExcel = (name: string, sheetData?: Array<Array<any>>) => {
  // name表示生成excel的文件名     tableName表示表格的dom元素的id值
  // const sel = XLSX.utils.table_to_book(document.querySelector(tableName));
  // const selIn = XLSX.write(sel, {bookType: 'xlsx', bookSST: true, type: 'array'});
  // try {
  //     FileSaver.saveAs(new Blob([selIn], { type: 'application/octet-stream' }), name)
  // } catch (e) {
  //     if (typeof console !== 'undefined') console.log(e, selIn)
  // }
  const sheetName1 = "sheet1";
  const aoa = sheetData
    ? sheetData
    : [
        ["姓名", "邮箱地址", "员工号", ""],
        ["测试", "test111@changan.com.cn", "000001", "示例(填写前请删除此行):"], // '示例(填写前请删除):',
      ];
  const worksheet = XLSX.utils.aoa_to_sheet(aoa);
  const workbook = {
    SheetNames: [sheetName1],
    Sheets: {
      [sheetName1]: worksheet, // sheet的名称一定要对应上
    },
  };
  /* 获取二进制字符串作为输出 */
  const wbout = XLSX.write(workbook, {
    bookType: "xlsx",
    bookSST: true,
    type: "array",
  });
  try {
    FileSaver.saveAs(
      new Blob([wbout], {
        type: "application/octet-stream",
      }),
      // 设置导出文件名称
      name
    );
  } catch (e) {
    if (typeof console !== "undefined") console.log(e, wbout);
  }
  return wbout;

  // return selIn
};

export const filterExcelContentArr = (
  selectedArr: Array<any>,
  tableProps: Array<any>,
  tableHeader: tableHeader
) => {
  const tempArr: Array<string | null> = [];
  tableProps.map((item1: string) => {
    tempArr.push(tableHeader[item1]);
  });

  // const filteredArr = selectedArr.map((item) => {
  //   // 这里的过滤逻辑与之前一致
  //   const filteredItem = Object.keys(item)
  //     .filter((key) => tableProps.includes(key))
  //     .sort((a, b) => {
  //       return tableProps.indexOf(a) - tableProps.indexOf(b);
  //     })
  //     .map((key) => item[key]); // 提取值

  //   return filteredItem;
  // });

  const filteredArr = selectedArr.map((v) =>
    tableProps.map((j) => {
      return v[j];
    })
  );

  return [tempArr, ...filteredArr];

  // const filteredArr = selectedArr.map((item) => {
  //   const filteredItem = Object.keys(item)
  //     .filter((key) => journalTableProps.includes(key))
  //     .reduce((obj: any, key) => {
  //       obj[key] = item[key];
  //       return obj;
  //     }, {});
  //      // 对 `filteredItem` 中的子数组按照 `neededKeys` 的顺序排序
  // return filteredItem;
  //   return Object.values(filteredItem);
  // });

  // const filteredArr = selectedArr.map((item) => {
  //   // 这里的过滤逻辑与之前一致
  //   const filteredItem = Object.keys(item)
  //     .filter((key) => journalTableProps.includes(key))
  //     .map((key) => {
  //       return { key, value: item[key] };
  //     });

  //   // 对 `filteredItem` 中的子数组按照 `neededKeys` 的顺序排序
  //   filteredItem.sort((a, b) => {
  //     return journalTableProps.indexOf(a.key) - journalTableProps.indexOf(b.key);
  //   });

  //   return filteredItem;
  // });
};
export const downloadFile = (blob: Blob, fileName: string) => {
  // debugger;
  console.log("12", typeof blob);
  const link = document.createElement("a");
  link.href = window.URL.createObjectURL(blob);
  link.download = fileName;
  link.click();
};
type dlParams = {
  url: string;
  params: any;
  filename: string;
  config?: any;
};
// 通用下载方法
export const downloadGenerator = async (obj: dlParams) => {
  const { url, params, filename, config } = obj;
  let downloadLoadingInstance = Loading.service({
    text: "正在下载数据，请稍候",
    background: "rgba(0, 0, 0, 0.7)",
  });
  return cafReq(0, { baseURL })
    .post(url, params, {
      transformRequest: [
        (params: any) => {
          return tansParams(params);
        },
      ],
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      responseType: "blob",
      ...config,
    })
    .then(async (data: any) => {
      const isBlob = blobValidate(data);
      if (isBlob) {
        const blob = new Blob([data]);
        FileSaver.saveAs(blob, filename);
      } else {
        const resText = await data.text();
        const rspObj = JSON.parse(resText);
        const errMsg =
          getErrorCodeDesc(rspObj.code) || rspObj.msg || getErrorCodeDesc(5001);
        Message.error(errMsg);
      }
      downloadLoadingInstance.close();
    })
    .catch((err: any) => {
      console.error(err);
      Message.error("下载文件出现错误，请联系管理员！");
      downloadLoadingInstance.close();
    });
};
